#!/usr/bin/python
# -*- coding:utf-8 -*-

'''This tool read session values from stdin, write bash alias
command to stdout, line by line.
The input lines should be like(<TAB> separated):
<Name><TAB><Protocol><TAB><AgentFwd><TAB><Password>
'''
import sys
import string

PUTTY_EXE='/c/software/putty/PUTTY.EXE'
ACCOUNT_FILE='c:/git_repository/notes/account.txt'

def main():
    for line in sys.stdin:
        line = line.strip('\r\n')
        if line:
            Name, Protocol, AgentFwd, Password = line.split('\t')
            CmdName = NormalizeCmd(Name)
            if Protocol == "ssh" and AgentFwd == "0":
                if Password.startswith('[') and Password.endswith(']'):
                    Password = getpasswd(Password[1:-1])
            if Password:
                print '''alias %s="%s -load '%s' -pw '%s' &"  ''' % (CmdName, PUTTY_EXE, Name, Password)
            else:
                print '''alias %s="%s -load '%s' & "  ''' % (CmdName, PUTTY_EXE, Name)
    return 0

def NormalizeCmd(name):
    return ''.join(c if is_valid_cmd_char(c) else '_' for c in name)

def is_valid_cmd_char(char):
    return char in string.letters or char in string.digits or char == '_'

def getpasswd(app):
    for line in open(ACCOUNT_FILE):
        items = line.rstrip('\r\n').split('\t')
        if items[0] == app:
            return items[2]
    else:
        return None
    
if __name__ == "__main__":
    sys.exit(main())
    

